//
//  ContentView.swift
//  todolist
//
//  Created by lizhixiang on 2025/3/12.
//

import SwiftUI

struct TodoItem: Identifiable, Codable {
    var id = UUID()
    var title: String
    var isCompleted: Bool = false
    var dueDate: Date?
    var priority: Priority = .normal
    var notes: String?
    
    enum Priority: Int, Codable, CaseIterable {
        case low = 0
        case normal = 1
        case high = 2
        
        var title: String {
            switch self {
            case .low: return "低"
            case .normal: return "中"
            case .high: return "高"
            }
        }
        
        var color: Color {
            switch self {
            case .low: return .blue
            case .normal: return .orange
            case .high: return .red
            }
        }
    }
}

class TodoStore: ObservableObject {
    @Published var todos: [TodoItem] = []
    
    init() {
        loadTodos()
    }
    
    func addTodo(_ todo: TodoItem) {
        todos.append(todo)
        saveTodos()
    }
    
    func updateTodo(at index: Int, with todo: TodoItem) {
        guard index >= 0 && index < todos.count else { return }
        todos[index] = todo
        saveTodos()
    }
    
    func toggleCompletion(at index: Int) {
        guard index >= 0 && index < todos.count else { return }
        todos[index].isCompleted.toggle()
        saveTodos()
    }
    
    func deleteTodo(at index: Int) {
        guard index >= 0 && index < todos.count else { return }
        todos.remove(at: index)
        saveTodos()
    }
    
    private func saveTodos() {
        if let encoded = try? JSONEncoder().encode(todos) {
            UserDefaults.standard.set(encoded, forKey: "savedTodos")
        }
    }
    
    private func loadTodos() {
        if let savedTodos = UserDefaults.standard.object(forKey: "savedTodos") as? Data {
            if let decodedTodos = try? JSONDecoder().decode([TodoItem].self, from: savedTodos) {
                todos = decodedTodos
                return
            }
        }
        
        // 默认任务
        todos = [
            TodoItem(title: "完成iOS应用开发", priority: .high, notes: "实现毛玻璃效果的TodoList"),
            TodoItem(title: "学习SwiftUI", priority: .normal),
            TodoItem(title: "阅读设计文档", priority: .low, notes: "了解iOS设计规范")
        ]
    }
}

struct TodoItemView: View {
    let todo: TodoItem
    let onToggle: () -> Void
    
    var body: some View {
        HStack {
            Button(action: onToggle) {
                Image(systemName: todo.isCompleted ? "checkmark.circle.fill" : "circle")
                    .foregroundColor(todo.isCompleted ? .green : .gray)
                    .font(.system(size: 20))
            }
            .buttonStyle(PlainButtonStyle())
            
            VStack(alignment: .leading, spacing: 4) {
                Text(todo.title)
                    .font(.headline)
                    .foregroundColor(todo.isCompleted ? .gray : .primary)
                    .strikethrough(todo.isCompleted)
                
                if let dueDate = todo.dueDate {
                    Text(dueDate, style: .date)
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
            }
            
            Spacer()
            
            Circle()
                .fill(todo.priority.color)
                .frame(width: 12, height: 12)
        }
        .padding(.vertical, 8)
        .padding(.horizontal, 12) // 增加内部水平边距
        .background(
            RoundedRectangle(cornerRadius: 10)
                .fill(Color.white.opacity(0.1))
                .background(
                    .ultraThinMaterial,
                    in: RoundedRectangle(cornerRadius: 10)
                )
        )
        .padding(.horizontal, 16) // 增加外部水平边距
    }
}

struct TodoDetailView: View {
    @Environment(\.dismiss) private var dismiss
    @Binding var todo: TodoItem
    let onSave: (TodoItem) -> Void
    
    // 恢复状态变量，但使用todo初始化
    @State private var title: String
    @State private var notes: String
    @State private var priority: TodoItem.Priority
    @State private var dueDate: Date
    @State private var hasDueDate: Bool
    
    init(todo: Binding<TodoItem>, onSave: @escaping (TodoItem) -> Void) {
        self._todo = todo
        self.onSave = onSave
        
        // 使用初始值设置本地状态
        _title = State(initialValue: todo.wrappedValue.title)
        _notes = State(initialValue: todo.wrappedValue.notes ?? "")
        _priority = State(initialValue: todo.wrappedValue.priority)
        _dueDate = State(initialValue: todo.wrappedValue.dueDate ?? Date())
        _hasDueDate = State(initialValue: todo.wrappedValue.dueDate != nil)
    }
    
    var body: some View {
        NavigationView {
            ZStack {
                Color.black.opacity(0.05).edgesIgnoringSafeArea(.all)
                
                Form {
                    Section(header: Text("任务信息")) {
                        TextField("标题", text: $title)
                        
                        Picker("优先级", selection: $priority) {
                            ForEach(TodoItem.Priority.allCases, id: \.self) { priority in
                                Text(priority.title).tag(priority)
                            }
                        }
                        .pickerStyle(SegmentedPickerStyle())
                        
                        Toggle("设置截止日期", isOn: $hasDueDate)
                        
                        if hasDueDate {
                            DatePicker("截止日期", selection: $dueDate, displayedComponents: [.date, .hourAndMinute])
                        }
                    }
                    .listRowBackground(Color.clear)
                    
                    Section(header: Text("备注")) {
                        TextEditor(text: $notes)
                            .frame(minHeight: 100)
                    }
                    .listRowBackground(Color.clear)
                }
                .background(Color.clear)
            }
            .navigationTitle(todo.id == UUID() ? "新建任务" : "编辑任务")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("取消") {
                        dismiss()
                    }
                }
                
                ToolbarItem(placement: .confirmationAction) {
                    Button("保存") {
                        // 在保存时将本地状态同步到todo
                        var updatedTodo = todo
                        updatedTodo.title = title
                        updatedTodo.notes = notes.isEmpty ? nil : notes
                        updatedTodo.priority = priority
                        updatedTodo.dueDate = hasDueDate ? dueDate : nil
                        
                        onSave(updatedTodo)
                        dismiss()
                    }
                    .disabled(title.isEmpty)
                }
            }
        }
    }
}

struct ContentView: View {
    @StateObject private var todoStore = TodoStore()
    @State private var showingAddTodo = false
    @State private var editingTodoIndex: Int?
    @State private var showingEditSheet = false
    @State private var currentEditingTodo: TodoItem?
    
    var body: some View {
        NavigationView {
            ZStack {
                // 渐变背景色替代背景图片
                LinearGradient(
                    gradient: Gradient(colors: [Color.blue.opacity(0.5), Color.purple.opacity(0.7)]),
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
                .edgesIgnoringSafeArea(.all)
                
                // 毛玻璃效果
                VStack {
                    Rectangle()
                        .fill(.ultraThinMaterial)
                        .edgesIgnoringSafeArea(.all)
                }
                
                VStack {
                    if todoStore.todos.isEmpty {
                        VStack {
                            Image(systemName: "checkmark.circle")
                                .font(.system(size: 60))
                                .foregroundColor(.gray)
                                .padding()
                            
                            Text("暂无待办事项")
                                .font(.title2)
                                .foregroundColor(.gray)
                        }
                        .frame(maxWidth: .infinity, maxHeight: .infinity)
                    } else {
                        List {
                            ForEach(Array(todoStore.todos.enumerated()), id: \.element.id) { index, todo in
                                TodoItemView(todo: todo, onToggle: {
                                    todoStore.toggleCompletion(at: index)
                                })
                                .listRowBackground(Color.clear)
                                .listRowSeparator(.hidden)
                                .listRowInsets(EdgeInsets(top: 4, leading: 0, bottom: 4, trailing: 0))
                                .swipeActions(edge: .trailing) {
                                    Button(role: .destructive) {
                                        todoStore.deleteTodo(at: index)
                                    } label: {
                                        Label("删除", systemImage: "trash")
                                    }
                                }
                                .onTapGesture {
                                    // 使用更简单的方式：先设置索引，然后在sheet显示前准备数据
                                    editingTodoIndex = index
                                    
                                    // 强制UI更新后再显示编辑视图
                                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                                        // 确保索引有效
                                        if index < todoStore.todos.count {
                                            // 创建一个全新的副本
                                            currentEditingTodo = TodoItem(
                                                id: todo.id,
                                                title: todo.title,
                                                isCompleted: todo.isCompleted,
                                                dueDate: todo.dueDate,
                                                priority: todo.priority,
                                                notes: todo.notes
                                            )
                                            showingEditSheet = true
                                        }
                                    }
                                }
                            }
                        }
                        .listStyle(PlainListStyle())
                        .background(Color.clear)
                        .padding(.horizontal, 0)
                    }
                }
                .padding(.horizontal, 0)
            }
            .navigationTitle("待办事项")
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button {
                        showingAddTodo = true
                    } label: {
                        Image(systemName: "plus.circle.fill")
                            .font(.system(size: 24))
                    }
                }
            }
            .sheet(isPresented: $showingAddTodo) {
                TodoDetailView(
                    todo: .constant(TodoItem(title: "")),
                    onSave: { newTodo in
                        todoStore.addTodo(newTodo)
                    }
                )
            }
            .sheet(isPresented: $showingEditSheet, onDismiss: {
                // 清理状态
                currentEditingTodo = nil
                editingTodoIndex = nil
            }) {
                if let todo = currentEditingTodo, let index = editingTodoIndex {
                    TodoDetailView(
                        todo: Binding(
                            get: { todo },
                            set: { newValue in
                                currentEditingTodo = newValue
                            }
                        ),
                        onSave: { updatedTodo in
                            // 确保索引仍然有效
                            if index < todoStore.todos.count {
                                todoStore.updateTodo(at: index, with: updatedTodo)
                            }
                        }
                    )
                }
            }
        }
        .navigationViewStyle(StackNavigationViewStyle())
    }
}

extension TodoItem: Equatable {
    static func == (lhs: TodoItem, rhs: TodoItem) -> Bool {
        lhs.id == rhs.id
    }
}

extension TodoItem: Hashable {
    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }
}

#Preview {
    ContentView()
}

// Remove the extension below
// extension View {
//     @ViewBuilder
//     func `if`<Content: View>(_ condition: Bool, transform: (Self) -> Content) -> some View {
//         if condition {
//             transform(self)
//         } else {
//             self
//         }
//     }
//     
//     @ViewBuilder
//     func `if`<Content: View>(_ condition: @autoclosure () -> Bool, transform: (Self) -> Content) -> some View {
//         if condition() {
//             transform(self)
//         } else {
//             self
//         }
//     }
// }
